import React, { useState, useEffect } from 'react';
import { 
  Box, 
  Typography, 
  Paper, 
  Table, 
  TableBody, 
  TableCell, 
  TableContainer, 
  TableHead, 
  TableRow,
  Button,
  IconButton,
  Tooltip,
  useTheme,
  CircularProgress,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  TextField,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  SelectChangeEvent,
  Snackbar,
  Alert,
  Chip,
  DialogContentText
} from '@mui/material';
import { 
  ArrowBack as ArrowBackIcon,
  Edit as EditIcon,
  Delete as DeleteIcon,
  Add as AddIcon,
  Check as CheckIcon
} from '@mui/icons-material';
import { useNavigate } from 'react-router-dom';
import { auth } from '../services/api';

interface User {
  id: number;
  username: string;
  email: string;
  role: string;
  created_at: string;
  password?: string;
}

interface DialogState {
  open: boolean;
  type: 'add' | 'edit' | null;
  user: User | null;
}

const UserManagement: React.FC = () => {
  const [users, setUsers] = useState<User[]>([]);
  const [loading, setLoading] = useState(true);
  const [dialogState, setDialogState] = useState<DialogState>({ open: false, type: null, user: null });
  const [formData, setFormData] = useState<Partial<User>>({});
  const [snackbar, setSnackbar] = useState({ open: false, message: '', severity: 'success' as 'success' | 'error' });
  const [deleteConfirmOpen, setDeleteConfirmOpen] = useState(false);
  const [userToDelete, setUserToDelete] = useState<number | null>(null);
  const navigate = useNavigate();
  const theme = useTheme();

  // 加载用户列表
  const loadUsers = async () => {
    try {
      setLoading(true);
      const response = await auth.getUsers();
      setUsers(response.data);
      setLoading(false);
    } catch (error) {
      console.error('加载用户列表失败:', error);
      setSnackbar({
        open: true,
        message: '加载用户列表失败，请检查网络连接或权限',
        severity: 'error'
      });
      setLoading(false);
    }
  };

  useEffect(() => {
    loadUsers();
  }, []);

  const formatDate = (dateString: string) => {
    const date = new Date(dateString);
    return date.toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: 'long',
      day: 'numeric'
    });
  };

  const handleOpenDialog = (type: 'add' | 'edit', user: User | null = null) => {
    setDialogState({ open: true, type, user });
    
    if (type === 'edit' && user) {
      setFormData({
        username: user.username,
        email: user.email,
        role: user.role
      });
    } else {
      setFormData({
        username: '',
        email: '',
        role: 'user',
        password: '' // 添加用户需要密码
      });
    }
  };

  const handleCloseDialog = () => {
    setDialogState({ open: false, type: null, user: null });
    setFormData({});
  };

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    setFormData(prev => ({ ...prev, [name]: value }));
  };

  const handleRoleChange = (e: SelectChangeEvent) => {
    setFormData(prev => ({ ...prev, role: e.target.value }));
  };

  const handleSaveUser = async () => {
    try {
      if (dialogState.type === 'add') {
        // 添加新用户
        if (!formData.username || !formData.email || !formData.password) {
          setSnackbar({
            open: true, 
            message: '请填写所有必填字段',
            severity: 'error'
          });
          return;
        }
        
        const response = await auth.addUser({
          username: formData.username,
          email: formData.email,
          password: formData.password as string,
          role: formData.role
        });
        
        setSnackbar({ 
          open: true, 
          message: '用户添加成功', 
          severity: 'success' 
        });
        loadUsers(); // 重新加载用户列表
      } else if (dialogState.type === 'edit' && dialogState.user) {
        // 更新用户信息
        const updateData: any = {};
        if (formData.username !== dialogState.user.username) updateData.username = formData.username;
        if (formData.email !== dialogState.user.email) updateData.email = formData.email;
        if (formData.role !== dialogState.user.role) updateData.role = formData.role;
        if (formData.password) updateData.password = formData.password;
        
        await auth.updateUser(dialogState.user.id, updateData);
        
        setSnackbar({ 
          open: true, 
          message: '用户信息已更新', 
          severity: 'success' 
        });
        loadUsers(); // 重新加载用户列表
      }
      
      handleCloseDialog();
    } catch (error: any) {
      console.error('保存用户信息失败:', error);
      setSnackbar({
        open: true,
        message: error.response?.data?.error || '操作失败，请重试',
        severity: 'error'
      });
    }
  };

  const openDeleteConfirmDialog = (userId: number) => {
    setUserToDelete(userId);
    setDeleteConfirmOpen(true);
  };

  const handleDeleteUser = async () => {
    if (!userToDelete) return;
    
    try {
      await auth.deleteUser(userToDelete);
      setSnackbar({ 
        open: true, 
        message: '用户已删除', 
        severity: 'success' 
      });
      loadUsers(); // 重新加载用户列表
    } catch (error: any) {
      console.error('删除用户失败:', error);
      setSnackbar({
        open: true,
        message: error.response?.data?.error || '删除失败，请重试',
        severity: 'error'
      });
    } finally {
      setDeleteConfirmOpen(false);
      setUserToDelete(null);
    }
  };

  const handleCloseSnackbar = () => {
    setSnackbar({ ...snackbar, open: false });
  };

  return (
    <Box sx={{ p: 3, maxWidth: 1200, margin: '0 auto' }}>
      <Box sx={{ display: 'flex', alignItems: 'center', mb: 4 }}>
        <IconButton onClick={() => navigate('/chat')} sx={{ mr: 2 }}>
          <ArrowBackIcon />
        </IconButton>
        <Typography variant="h5" component="h1">
          用户管理
        </Typography>
        <Button 
          variant="contained" 
          startIcon={<AddIcon />}
          sx={{ ml: 'auto' }}
          onClick={() => handleOpenDialog('add')}
        >
          添加用户
        </Button>
      </Box>

      <Paper sx={{ width: '100%', overflow: 'hidden' }}>
        {loading ? (
          <Box sx={{ display: 'flex', justifyContent: 'center', p: 4 }}>
            <CircularProgress />
          </Box>
        ) : (
          <TableContainer>
            <Table>
              <TableHead>
                <TableRow>
                  <TableCell>ID</TableCell>
                  <TableCell>用户名</TableCell>
                  <TableCell>邮箱</TableCell>
                  <TableCell>角色</TableCell>
                  <TableCell>注册时间</TableCell>
                  <TableCell align="right">操作</TableCell>
                </TableRow>
              </TableHead>
              <TableBody>
                {users.length === 0 ? (
                  <TableRow>
                    <TableCell colSpan={6} align="center">
                      暂无用户数据
                    </TableCell>
                  </TableRow>
                ) : (
                  users.map((user) => (
                    <TableRow key={user.id}>
                      <TableCell>{user.id}</TableCell>
                      <TableCell>{user.username}</TableCell>
                      <TableCell>{user.email}</TableCell>
                      <TableCell>
                        <Chip 
                          label={user.role === 'admin' ? '管理员' : '普通用户'} 
                          color={user.role === 'admin' ? 'primary' : 'default'}
                          size="small"
                        />
                      </TableCell>
                      <TableCell>{formatDate(user.created_at)}</TableCell>
                      <TableCell align="right">
                        <Tooltip title="编辑">
                          <IconButton 
                            size="small"
                            onClick={() => handleOpenDialog('edit', user)}
                          >
                            <EditIcon fontSize="small" />
                          </IconButton>
                        </Tooltip>
                        <Tooltip title="删除">
                          <IconButton 
                            size="small" 
                            sx={{ color: 'error.main' }}
                            onClick={() => openDeleteConfirmDialog(user.id)}
                          >
                            <DeleteIcon fontSize="small" />
                          </IconButton>
                        </Tooltip>
                      </TableCell>
                    </TableRow>
                  ))
                )}
              </TableBody>
            </Table>
          </TableContainer>
        )}
      </Paper>

      {/* 添加/编辑用户对话框 */}
      <Dialog 
        open={dialogState.open} 
        onClose={handleCloseDialog}
        maxWidth="sm"
        fullWidth
      >
        <DialogTitle>
          {dialogState.type === 'add' ? '添加新用户' : '编辑用户信息'}
        </DialogTitle>
        <DialogContent>
          <Box sx={{ pt: 2, display: 'flex', flexDirection: 'column', gap: 2 }}>
            <TextField
              fullWidth
              label="用户名"
              name="username"
              value={formData.username || ''}
              onChange={handleInputChange}
              required
            />
            <TextField
              fullWidth
              label="邮箱"
              name="email"
              type="email"
              value={formData.email || ''}
              onChange={handleInputChange}
              required
            />
            <TextField
              fullWidth
              label="密码"
              name="password"
              type="password"
              value={formData.password || ''}
              onChange={handleInputChange}
              required={dialogState.type === 'add'}
              helperText={dialogState.type === 'edit' ? '如不修改密码请留空' : ''}
            />
            <FormControl fullWidth>
              <InputLabel id="role-select-label">用户角色</InputLabel>
              <Select
                labelId="role-select-label"
                id="role-select"
                value={formData.role || 'user'}
                label="用户角色"
                onChange={handleRoleChange}
              >
                <MenuItem value="user">普通用户</MenuItem>
                <MenuItem value="admin">管理员</MenuItem>
              </Select>
            </FormControl>
          </Box>
        </DialogContent>
        <DialogActions>
          <Button onClick={handleCloseDialog}>取消</Button>
          <Button 
            variant="contained"
            onClick={handleSaveUser}
            startIcon={<CheckIcon />}
          >
            保存
          </Button>
        </DialogActions>
      </Dialog>

      {/* 删除确认对话框 */}
      <Dialog
        open={deleteConfirmOpen}
        onClose={() => setDeleteConfirmOpen(false)}
      >
        <DialogTitle>确认删除</DialogTitle>
        <DialogContent>
          <DialogContentText>
            确定要删除此用户吗？此操作不可撤销。
          </DialogContentText>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setDeleteConfirmOpen(false)}>取消</Button>
          <Button onClick={handleDeleteUser} color="error">
            删除
          </Button>
        </DialogActions>
      </Dialog>

      {/* 操作反馈提示 */}
      <Snackbar 
        open={snackbar.open} 
        autoHideDuration={3000} 
        onClose={handleCloseSnackbar}
        anchorOrigin={{ vertical: 'bottom', horizontal: 'center' }}
      >
        <Alert 
          onClose={handleCloseSnackbar} 
          severity={snackbar.severity}
          sx={{ width: '100%' }}
        >
          {snackbar.message}
        </Alert>
      </Snackbar>
    </Box>
  );
};

export default UserManagement; 